package com.sddnytsh.body_buildingsystem.utils

import androidx.navigation.NavController

/**
 * 导航扩展函数 - 防止重复压栈
 * 使用栈顶判重 + launchSingleTop + popUpTo 确保同一页面只保留一个实例
 */

/**
 * 导航到评论详情页面，防止重复压栈
 * @param commentId 评论ID
 */
fun NavController.navigateCommentDetail(commentId: Long) {
    val route = "comment_detail/$commentId"
    val currentRoute = currentBackStackEntry?.destination?.route
    
    android.util.Log.d("NavExt", "=== 导航检查开始 ===")
    android.util.Log.d("NavExt", "目标路由: $route")
    android.util.Log.d("NavExt", "当前路由: $currentRoute")
    android.util.Log.d("NavExt", "commentId: $commentId")
    
    // 栈顶判重：如果已经在目标页面，直接返回
    if (currentRoute == route) {
        android.util.Log.d("NavExt", "已在目标页面，跳过导航 - commentId: $commentId")
        return
    }
    
    android.util.Log.d("NavExt", "执行导航 - commentId: $commentId")
    navigate(route) {
        launchSingleTop = true
        popUpTo(route) { inclusive = true }
    }
    android.util.Log.d("NavExt", "=== 导航检查结束 ===")
}

/**
 * 导航到帖子详情页面，防止重复压栈
 * @param postId 帖子ID
 */
fun NavController.navigatePostDetail(postId: Int) {
    val route = "postDetail/$postId"
    val currentRoute = currentBackStackEntry?.destination?.route
    
    // 栈顶判重：如果已经在目标页面，直接返回
    if (currentRoute == route) {
        android.util.Log.d("NavExt", "已在目标页面，跳过导航 - postId: $postId")
        return
    }
    
    android.util.Log.d("NavExt", "导航到帖子详情页面 - postId: $postId")
    navigate(route) {
        launchSingleTop = true
        popUpTo(route) { inclusive = true }
    }
}
